package com.gitee.wsl.struct.node

import kotlinx.atomicfu.atomic
import kotlin.jvm.JvmField

open class Node<T> {
    /**
     * A unique identifier, used to distinguish or compare the tree nodes
     */
    @JvmField
    protected val nodeId = ID_GENERATOR.getAndIncrement()

    /**
     * Data store in the current tree node
     */
    var data: T? = null

    constructor() {}
    constructor(data: T) {
        this.data = data
    }

    /**
     * Indicates whether some object equals to this one
     *
     * @param obj the reference object with which to compare
     * @return `true` if this object is the same as the obj
     * argument; `false` otherwise
     */
    override fun equals(obj: Any?): Boolean {
        if (this === obj) {
            return true
        }
        if (obj == null || this::class != obj::class) {
            return false
        }
        val that = obj as Node<*>
        return nodeId == that.nodeId
    }

    override fun hashCode(): Int {
        var result = nodeId
        result = 31 * result + (data?.hashCode() ?: 0)
        return result
    }

    companion object {
        /**
         * Identifier generator, used to get a unique id for each created tree node
         */
        protected val ID_GENERATOR = atomic(0)
    }
}